package org.example.ExperimentFour.Second;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
//动态工厂模式
public class DataServiceFactory {
    private static final Map<String, String> databaseMappings = new HashMap<>();
    static {
        // 从配置文件中读取数据库名称和对应的DataService类名，并存储到映射表中
        databaseMappings.put("MySql", "MySqlDataService");
        databaseMappings.put("MongoDB", "MongoDBDataService");
        databaseMappings.put("Redis", "RedisDataService");
    }
    public static DataService createDataService(String databaseName) throws Exception {
        // 从映射表中获取对应的DataService类名
        String dataServiceClassName = databaseMappings.get(databaseName);
        System.out.println(dataServiceClassName); // 输出正确
        if (dataServiceClassName != null) {
            try {
//               返回一个工厂模式后的实例对象
                Class<?> dataServiceClass = Class.forName("org.example.ExperimentFour.Second."+dataServiceClassName);
                Constructor<?> constructor = dataServiceClass.getDeclaredConstructor();
                return (DataService) constructor.newInstance();
            } catch (ClassNotFoundException e) {
                // 记录异常并进行错误处理
                System.err.println("没有找到类: " + dataServiceClassName);
                throw new ClassNotFoundException("没有找到类: " + dataServiceClassName, e);
            }
        } else {
            throw new IllegalArgumentException("数据库不支持: " + databaseName);
        }
    }

}
